<?php

namespace app\admin\controller\kzvote;

use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Log extends Backend
{

    /**
     * Log模型对象
     * @var \app\common\model\kzvote\Log
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\kzvote\Log;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['vote','person','user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('vote')->visible(['name']);
				$row->getRelation('person')->visible(['name']);
				$row->getRelation('user')->visible(['nickname,avatar']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 导出
     */
    public function export(){
        $this->relationSearch = true;

        if ($this->request->isPost()) {
            set_time_limit(0);
            $search = $this->request->post('search');
            $ids = $this->request->post('ids');
            $filter = $this->request->post('filter');
            $op = $this->request->post('op');
            $columns = $this->request->post('columns');

            $whereIds = $ids == 'all' ? '1=1' : ['log.id' => ['in', explode(',', $ids)]];
            $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            //设置过滤方法
            $this->request->filter(['strip_tags']);

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            //开始制作表格
            $spreadsheet = new Spreadsheet();
            $spreadsheet->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
            $spreadsheet->getDefaultStyle()->getFont()->setSize(12);
            $spreadsheet->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
            $spreadsheet->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
            $spreadsheet->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
            $spreadsheet->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);

            $worksheet = $spreadsheet->setActiveSheetIndex(0);

            $file_name = '投票记录导出'.date('Y-m-d');

            $worksheet->getCell('A1')->setValue('投票活动');
            $worksheet->getCell('B1')->setValue('作品名称');
            $worksheet->getCell('C1')->setValue('投票用户');
            $worksheet->getCell('D1')->setValue('投票ip');
            $worksheet->getCell('E1')->setValue('投票方式');
            $worksheet->getCell('F1')->setValue('票数');
            $worksheet->getCell('G1')->setValue('投票时间');
            $worksheet->getCell('H1')->setValue('表单内容');
            $worksheet->getCell('I1')->setValue('手机号');

            $ABC = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];

            $list = $this->model->alias('log')
                ->with(['vote','person','user'])
                ->where($whereIds)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $arr = [];
            foreach ($list as $key => $val) {
                $form = '';
                if ($val['join_form']){
                    foreach ($val['join_form'] as $k=>$row){
                        $form .= $k.":".$row."​\n​";
                    }
                }

                $data = array($val['vote']['name'], $val['person']['name'], $val['user']['nickname'],$val['ip'],$val['type_text']
                ,$val['num'], date('Y-m-d H:i:s',$val['createtime']), $form, $val['user']['mobile']);

                array_push($arr, $data);
            }

            foreach ($arr as $key => $row) {
                foreach ($ABC as $k => $r) {
                    $worksheet->getCell($ABC[$k] . ($key + 2))->setValue($row[$k]);
                }
            }
            $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
            //下载文档
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $file_name . '.xlsx"');
            header('Cache-Control: max-age=0');
            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $writer->save('php://output');
        }
    }


}
